package A099queue;

/**
 * SynchronousQueue没有容量。
 * <p>
 * 与其他BlockingQueue不同，SynchronousQueue是一个不存储元素的BlockingQueue。
 * <p>
 * 每一个put操作必须要等待一个take操作，否则不能继续添加元素，反之亦然。
 */

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class C002_SynchronousQueue_offer_poll_不报错_无法插入和获取 {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                boolean a = blockingQueue.offer("A");
                System.out.println(Thread.currentThread().getName() + "\t offer A =" + a);


                boolean b = blockingQueue.offer("B");
                System.out.println(Thread.currentThread().getName() + "\t offer B =" + b);

                boolean c = blockingQueue.offer("C");
                System.out.println(Thread.currentThread().getName() + "\t offer C =" + c);


            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            try {

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String a = blockingQueue.poll();
                System.out.println(Thread.currentThread().getName() + "\t take A =" + a);

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String b = blockingQueue.poll();
                System.out.println(Thread.currentThread().getName() + "\t take B =" + b);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

}
